home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5092 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.3 KB

  1. Path: news.lpr.carel.fi!usenet
  2. From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: External access to private class variables
  5. Date: Fri, 02 Feb 1996 14:57:18 +0200
  6. Organization: Carelcomp Forest
  7. Message-ID: <31120A2E.59D1@cmt.lpr.mail.carel.fi>
  8. References: <4ermr9$ii7@cloner2.ix.netcom.com>
  9. NNTP-Posting-Host: renoir.cclahti.carel.fi
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b6a (WinNT; I)
  14.  
  15. Eugene S. Thompson wrote:
  16. > I was playing around with references and ran across this situation. I'm
  17. > sure it's not original, so I was hoping someone could tell me if it is
  18. > an intentional implementation of C++ or if it is a bug.
  19. > class X
  20. > {
  21. > private:
  22. >     int value;
  23. > public:
  24. >     X (int n = 0) { value = n; }
  25. >     int& GSValue () { return value; }   // return a reference to the
  26. >                                         // private member "value"
  27. > };
  28. >     .
  29. >     .
  30. >     .
  31. > main ()
  32. > {
  33. > X   x1 (20);
  34. >     printf ("%d\n", x1.GSValue ());     // 20
  35. > int* pntr = &(x1.GSValue ());
  36. >     printf ("%d\n", *pntr);             // 20
  37. >     *pntr = 30;
  38. >     printf ("%d\n", x1.GSValue ());     // 30 -> We now have external
  39. >                                         // access to a private member.
  40. > }
  41. > I realize that this implementation is contrived, but I'm sure there are
  42. > additional ways of gaining such access. So, what's the deal?
  43. > Gene
  44.  
  45. This is normal behaviour. Only, using such constructs is a bad programming 
  46. practice, since the meaning of declaring a variable as private is to disallow 
  47. direct access to it. What if you compiled this class and produced a library that 
  48. other people can use. Later, you found out that you'll have to change 'int value;' 
  49. to 'char value[10];'. Now, if you had declared access functions (GetValue, 
  50. SetValue) that internally get/set the value, you could just modify the passed 
  51. value to suit the new format. But if you allowed your library users gain direct 
  52. access to it, they'd also have to change all their code directly using that 
  53. variable. Instead of
  54.  
  55.      int& GSValue () { return value; }
  56.  
  57. you should use
  58.  
  59.     const int& GSValue() { return value; }
  60.  
  61. That can still be called, but now the callers cannot modify what you gave them.
  62.  
  63. Later,
  64.  AriL
  65.  
  66. -- 
  67. All my opinions are mine and mine alone.
  68.